<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="lambda," />




  


  <link rel="alternate" href="/atom.xml" title="Richey's Blog" type="application/atom+xml" />






<meta name="description" content="1、Java Stream API 入门Java8引入函数式编程 代码简洁，使用stream接口让你从此告别for循环 多核友好，Java函数式编程使得编写并行程序从未如此简单，你需要的全部就是调用一下parallel()方法  Java函数式编程的主角 Stream stream并不是某种数据结构，它只是&#x3D;&#x3D;数据源的一种视图&#x3D;&#x3D;。这里的数据源可以是一个数组，Java容器或I&#x2F;O channel等">
<meta property="og:type" content="article">
<meta property="og:title" content="Java Stream">
<meta property="og:url" content="http://10000hours.top/2019/03/08/Java%20Stream/index.html">
<meta property="og:site_name" content="Richey&#39;s Blog">
<meta property="og:description" content="1、Java Stream API 入门Java8引入函数式编程 代码简洁，使用stream接口让你从此告别for循环 多核友好，Java函数式编程使得编写并行程序从未如此简单，你需要的全部就是调用一下parallel()方法  Java函数式编程的主角 Stream stream并不是某种数据结构，它只是&#x3D;&#x3D;数据源的一种视图&#x3D;&#x3D;。这里的数据源可以是一个数组，Java容器或I&#x2F;O channel等">
<meta property="og:image" content="http://orybhlel7.bkt.clouddn.com/image/png/stream-interface.png">
<meta property="article:published_time" content="2019-03-07T16:00:00.000Z">
<meta property="article:modified_time" content="2020-05-19T14:54:59.043Z">
<meta property="article:author" content="Richey Liu">
<meta property="article:tag" content="lambda">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://orybhlel7.bkt.clouddn.com/image/png/stream-interface.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://10000hours.top/2019/03/08/Java Stream/"/>





  <title>Java Stream | Richey's Blog</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Richey's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">吾生也有涯，而知也无涯。以有涯随无涯，殆已。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://10000hours.top/2019/03/08/Java%20Stream/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Richey Liu">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Richey's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java Stream</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-08T00:00:00+08:00">
                2019-03-08
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java-%E5%9F%BA%E7%A1%80/" itemprop="url" rel="index">
                    <span itemprop="name">Java 基础</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/03/08/Java%20Stream/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/03/08/Java%20Stream/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2019/03/08/Java%20Stream/" class="leancloud_visitors" data-flag-title="Java Stream">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="1、Java-Stream-API-入门"><a href="#1、Java-Stream-API-入门" class="headerlink" title="1、Java Stream API 入门"></a>1、Java Stream API 入门</h1><h2 id="Java8引入函数式编程"><a href="#Java8引入函数式编程" class="headerlink" title="Java8引入函数式编程"></a>Java8引入函数式编程</h2><ul>
<li>代码简洁，使用stream接口让你从此告别for循环</li>
<li>多核友好，Java函数式编程使得编写并行程序从未如此简单，你需要的全部就是调用一下parallel()方法</li>
</ul>
<h2 id="Java函数式编程的主角-Stream"><a href="#Java函数式编程的主角-Stream" class="headerlink" title="Java函数式编程的主角 Stream"></a>Java函数式编程的主角 Stream</h2><blockquote>
<p>stream并不是某种数据结构，它只是==数据源的一种视图==。这里的数据源可以是一个数组，Java容器或I/O channel等。因如此要得到一个stream通常不会手动创建，而是调用对应的工具方法，比如：</p>
</blockquote>
<ul>
<li>调用Collection.stream()或者Collection.parallelStream()方法</li>
<li>stream(T[] array)方法</li>
<li>Stream 接口关系继承图</li>
</ul>
<p><img src="http://orybhlel7.bkt.clouddn.com/image/png/stream-interface.png" alt="image"></p>
<blockquote>
<p>图中4种stream接口继承自BaseStream，其中IntStream, LongStream, DoubleStream对应三种基本类型（int, long, double，注意不是包装类型），Stream对应所有剩余类型的stream视图</p>
</blockquote>
<h2 id="Stream的特点"><a href="#Stream的特点" class="headerlink" title="Stream的特点"></a>Stream的特点</h2><blockquote>
<p>虽然大部分情况下stream是容器调用Collection.stream()方法得到的，但stream和collections有以下不同：</p>
</blockquote>
<ul>
<li>==无存储==。stream不是一种数据结构，它只是某种数据源的一个视图，数据源可以是一个数组，Java容器或I/O channel等。</li>
<li>==为函数式编程而生==。对stream的任何修改都不会修改背后的数据源，比如对stream执行过滤操作并不会删除被过滤的元素，而是会产生一个不包含被过滤元素的新stream。</li>
<li>==惰式执行==。stream上的操作并不会立即执行，只有等到用户真正需要结果的时候才会执行。</li>
<li>==可消费性==。stream只能被“消费”一次，一旦遍历过就会失效，就像容器的迭代器那样，想要再次遍历必须重新生成。</li>
</ul>
<blockquote>
<p>对stream的操作分为为两类，==中间操作==(intermediate operations)和==结束操作==(terminal operations)，二者特点是：</p>
</blockquote>
<ol>
<li>中间操作总是会惰式执行，调用中间操作只会生成一个标记了该操作的新stream，仅此而已。</li>
<li>结束操作会触发实际计算，计算发生时会把所有中间操作积攒的操作以pipeline的方式执行，这样可以减少迭代次数。计算完成之后stream就会失效。</li>
</ol>
<h2 id="Stream常见方法"><a href="#Stream常见方法" class="headerlink" title="Stream常见方法"></a>Stream常见方法</h2><blockquote>
<p>Stream接口的部分常见方法：</p>
</blockquote>
<table>
<thead>
<tr>
<th>操作类型</th>
<th>接口方法</th>
</tr>
</thead>
<tbody><tr>
<td>中间操作</td>
<td>concat() distinct() filter() flatMap() limit() map() peek() skip() sorted() parallel() sequential() unordered()</td>
</tr>
<tr>
<td>结束操作</td>
<td>allMatch() anyMatch() collect() count() findAny() findFirst() forEach() forEachOrdered() max() min() noneMatch() reduce() toArray()</td>
</tr>
</tbody></table>
<p><strong>区分中间操作和结束操作最简单的方法，就是看方法的返回值，返回值为stream的大都是中间操作，否则是结束操作。</strong></p>
<h2 id="Stream方法的使用"><a href="#Stream方法的使用" class="headerlink" title="Stream方法的使用"></a>Stream方法的使用</h2><blockquote>
<p>stream跟函数接口关系非常紧密，没有函数接口stream就无法工作。回顾一下：==函数接口是指内部只有一个抽象方法的接口。通常函数接口出现的地方都可以使用Lambda表达式==，所以不必记忆函数接口的名字。   </p>
</blockquote>
<ul>
<li>forEach()    </li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;String&gt; stream &#x3D; Stream.of(&quot;I&quot;,&quot;love&quot;,&quot;yout&quot;,&quot;too&quot;);</span><br><span class="line">stream.forEach(str -&gt; System.out.println(str));</span><br></pre></td></tr></table></figure>
<pre><code>由于forEach()是结束方法，上述代码会立即执行，输出所有字符串。</code></pre><ul>
<li><p>filter()    </p>
<p>  函数原型为Stream<T> filter(Predicate&lt;? super T&gt; predicate)，作用是返回一个只包含满足predicate条件元素的Stream。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;String&gt; stream &#x3D; Stream.of(&quot;I&quot;,&quot;love&quot;,&quot;you&quot;,&quot;too&quot;);</span><br><span class="line">stream.filter(str -&gt; str.length() &#x3D;&#x3D; 3).forEach(str -&gt; System.out.println(str));</span><br></pre></td></tr></table></figure>
</li>
<li><p>distinck()</p>
<p>  函数原型为Stream<T> distinct()，作用是返回一个去除重复元素之后的Stream。</p>
</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;String&gt; stream &#x3D; Stream.of(&quot;I&quot;,&quot;love&quot;,&quot;you&quot;,&quot;too&quot;,&quot;too&quot;);</span><br><span class="line">stream.distinct().forEach(str -&gt; System.out.println(str));</span><br></pre></td></tr></table></figure>

<ul>
<li><p>sorted()</p>
<p>  排序函数有两个，一个是用自然顺序排序，一个是使用自定义比较器排序，函数原型分别为Stream<T>　sorted()和Stream<T>　sorted(Comparator&lt;? super T&gt; comparator)。</p>
</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;String&gt; stream &#x3D; Stream.of(&quot;I&quot;,&quot;love&quot;,&quot;you&quot;,&quot;too&quot;);</span><br><span class="line">stream.sorted((str1, str2) -&gt; str1.length() - str2.length()).forEach(str -&gt; System.out.println(str));</span><br></pre></td></tr></table></figure>

<ul>
<li>map()</li>
</ul>
<p>函数原型为<R> Stream<R> map(Function&lt;? super T,? extends R&gt; mapper)，作用是返回一个对当前所有元素执行执行mapper之后的结果组成的Stream。直观的说，就是对每个元素按照某种操作进行转换，转换前后Stream中元素的个数不会改变，但元素的类型取决于转换之后的类型。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;String&gt; stream &#x3D; Stream.of(&quot;I&quot;,&quot;love&quot;,&quot;you&quot;,&quot;too&quot;);</span><br><span class="line">stream.map(str -&gt; str.toUpperCase()).forEach(str -&gt; System.out.println(str));</span><br></pre></td></tr></table></figure>

<ul>
<li><p>flatMap</p>
<p>  函数原型为<R> Stream<R> flatMap(Function&lt;? super T,? extends Stream&lt;? extends R&gt;&gt; mapper)，作用是对每个元素执行mapper指定的操作，并用所有mapper返回的Stream中的元素组成一个新的Stream作为最终返回结果。说起来太拗口，通俗的讲flatMap()的作用就相当于把原stream中的所有元素都”摊平”之后组成的Stream，转换前后元素的个数和类型都可能会改变。</p>
</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;List&lt;Integer&gt;&gt; stream &#x3D; Stream.of(Arrays.asList(1, 2), Arrays.asList(3, 4));</span><br><span class="line">stream.flatMap(list -&gt; list.stream()).forEach(i -&gt; System.out.println(i));</span><br></pre></td></tr></table></figure>

<h1 id="2、Java-Stream-API-进阶"><a href="#2、Java-Stream-API-进阶" class="headerlink" title="2、Java Stream API 进阶"></a>2、Java Stream API 进阶</h1><h2 id="Stream的规约操作"><a href="#Stream的规约操作" class="headerlink" title="Stream的规约操作"></a>Stream的规约操作</h2><blockquote>
<p>规约操作（reduction operation）又被称作折叠操作（fold），是通过某个连接动作将所有元素汇总成一个汇总结果的过程。元素求和、求最大值或最小值、求出元素总个数、将所有元素转换成一个列表或集合，都属于规约操作。Stream类库有两个通用的规约操作reduce()和collect()，也有一些为简化书写而设计的专用规约操作，比如sum()、max()、min()、count()等。</p>
</blockquote>
<blockquote>
<p>最大或最小值这类规约操作很好理解（至少方法语义上是这样），我们着重介绍reduce()和collect()，这是比较有魔法的地方。</p>
</blockquote>
<h3 id="多面手reduce"><a href="#多面手reduce" class="headerlink" title="多面手reduce()"></a>多面手reduce()</h3><p>reduce操作可以实现从一组元素中生成一个值，sum()、max()、min()、count()等都是reduce操作，将他们单独设为函数只是因为常用。reduce()的方法定义有三种重写形式：</p>
<ul>
<li>Optional<T> reduce(BinaryOperator<T> accumulator)</li>
<li>T reduce(T identity, BinaryOperator<T> accumulator)</li>
<li><U> U reduce(U identity, BiFunction&lt;U,? super T,U&gt; accumulator, BinaryOperator<U> combiner)</li>
</ul>
<p>虽然函数定义越来越长，但语义不曾改变，多的参数只是为了指明初始值（参数identity），或者是指定并行执行时多个部分结果的合并方式（参数combiner）。reduce()最常用的场景就是从一堆值中生成一个值。用这么复杂的函数去求一个最大或最小值，你是不是觉得设计者有病。其实不然，因为“大”和“小”或者“求和”有时会有不同的语义。</p>
<p>需求：从一组单词中找出最长的单词。这里“大”的含义就是“长”。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;String&gt; stream &#x3D; Stream.of(&quot;I&quot;,&quot;love&quot;,&quot;you&quot;,&quot;too&quot;);</span><br><span class="line">Optional&lt;String&gt; longest &#x3D; stream.reduce((str1, str2) -&gt; str1.length() &gt; str2.length() ? str1 : str2);</span><br><span class="line">System.out.println(longest.get());</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;等同于</span><br><span class="line">Stream&lt;String&gt; stream &#x3D; Stream.of(&quot;I&quot;,&quot;love&quot;,&quot;you&quot;,&quot;too&quot;);</span><br><span class="line">Optional&lt;String&gt; longest &#x3D; stream.max((str1, str2) -&gt; str1.length() - str2.length());</span><br><span class="line">System.out.println(longest.get());</span><br></pre></td></tr></table></figure>
<p>上述代码会选出最长的单词love，其中Optional是（一个）值的容器，使用它可以避免null值的麻烦。当然可以使用Stream.max(Comparator&lt;? super T&gt; comparator)方法来达到同等效果，但reduce()自有其存在的理由。</p>
<p>需求：求出一组单词的长度之和。这是个“求和”操作，操作对象输入类型是String，而结果类型是Integer。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;String&gt; stream &#x3D; Stream.of(&quot;I&quot;,&quot;love&quot;,&quot;you&quot;,&quot;too&quot;);</span><br><span class="line">Integer lengthSum &#x3D; stream.reduce(0, &#x2F;&#x2F; 初始值 &#x2F;&#x2F;(1)</span><br><span class="line">        (sum, str) -&gt; sum + str.length(),  &#x2F;&#x2F;累加器 &#x2F;&#x2F;(2)</span><br><span class="line">        (a, b) -&gt; a + b); &#x2F;&#x2F;部分结果拼接器 &#x2F;&#x2F;(3)</span><br><span class="line">&#x2F;&#x2F;stream.mapToInt(str -&gt; str.length()).sum();</span><br><span class="line">System.out.println(lengthSum);</span><br></pre></td></tr></table></figure>
<p>上述代码标号(2)处将i. 字符串映射成长度，ii. 并和当前累加和相加。这显然是两步操作，使用reduce()函数将这两步合二为一，更有助于提升性能。如果想要使用map()和sum()组合来达到上述目的，也是可以的。</p>
<p>==reduce()擅长的是生成一个值==，如果想要从Stream生成一个集合或者Map等复杂的对象该怎么办呢？终极武器collect()横空出世！</p>
<h3 id="终极武器collect"><a href="#终极武器collect" class="headerlink" title="终极武器collect()"></a>终极武器collect()</h3><p>不夸张的讲，如果你发现某个功能在Stream接口中没找到，十有八九可以通过collect()方法实现。collect()是Stream接口方法中最灵活的一个，学会它才算真正入门Java函数式编程。先看几个热身的小例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;String&gt; stream &#x3D; Stream.of(&quot;I&quot;,&quot;love&quot;,&quot;you&quot;,&quot;too&quot;);</span><br><span class="line">List&lt;String&gt; list &#x3D; stream.collect(Collectors.toList());</span><br><span class="line">&#x2F;&#x2F;Set&lt;String&gt; set &#x3D; stream.collect(Collectors.toSet());</span><br><span class="line">&#x2F;&#x2F;Map&lt;String, Integer&gt; map &#x3D; stream.collect(Collectors.toMap(Function.identity(), String::length));</span><br></pre></td></tr></table></figure>

<p>上述代码分别列举了如何将Stream转换成List、Set和Map。虽然代码语义很明确，可是我们仍然会有几个疑问：</p>
<ul>
<li>Function.identity()是干什么的？</li>
<li>String::length是什么意思？</li>
<li>Collectors是个什么东西？</li>
</ul>
<h4 id="接口的静态方法和默认方法"><a href="#接口的静态方法和默认方法" class="headerlink" title="==接口的静态方法和默认方法=="></a>==接口的静态方法和默认方法==</h4><p>Function是一个接口，那么Function.identity()是什么意思呢？这要从两方面解释：</p>
<ol>
<li>Java 8允许在接口中加入具体方法。接口中的具体方法有两种，default方法和static方法，identity()就是Function接口的一个静态方法。</li>
<li>Function.identity()返回一个输出跟输入一样的Lambda表达式对象，等价于形如t -&gt; t形式的Lambda表达式。</li>
</ol>
<blockquote>
<p>上面的解释是不是让你疑问更多？不要问我为什么接口中可以有具体方法，也不要告诉我你觉得t -&gt; t比identity()方法更直观。我会告诉你接口中的default方法是一个无奈之举，在Java 7及之前要想在定义好的接口中加入新的抽象方法是很困难甚至不可能的，因为所有实现了该接口的类都要重新实现。试想在Collection接口中加入一个stream()抽象方法会怎样？default方法就是用来解决这个尴尬问题的，直接在接口中实现新加入的方法。既然已经引入了default方法，为何不再加入static方法来避免专门的工具类呢！</p>
</blockquote>
<h4 id="方法引用"><a href="#方法引用" class="headerlink" title="==方法引用=="></a>==方法引用==</h4><p>诸如String::length的语法形式叫做方法引用（method references），这种语法用来替代某些特定形式Lambda表达式。如果Lambda表达式的全部内容就是调用一个已有的方法，那么可以用方法引用来替代Lambda表达式。方法引用可以细分为四类：</p>
<table>
<thead>
<tr>
<th>方法引用类别</th>
<th>举例</th>
</tr>
</thead>
<tbody><tr>
<td>引用静态方法</td>
<td>Integer::sum</td>
</tr>
<tr>
<td>引用某个对象的方法</td>
<td>list::add</td>
</tr>
<tr>
<td>引用某个类的方法</td>
<td>String::length</td>
</tr>
<tr>
<td>引用构造方法</td>
<td>HashMap::new</td>
</tr>
</tbody></table>
<h4 id="收集器"><a href="#收集器" class="headerlink" title="==收集器=="></a>==收集器==</h4><p>收集器（Collector）是为Stream.collect()方法量身打造的工具接口（类）。考虑一下将一个Stream转换成一个容器（或者Map）需要做哪些工作？我们至少需要两样东西：</p>
<ol>
<li>目标容器是什么？是ArrayList还是HashSet，或者是个TreeMap。</li>
<li>新元素如何添加到容器中？是List.add()还是Map.put()。如果并行的进行规约，还需要告诉collect()</li>
<li>多个部分结果如何合并成一个。</li>
</ol>
<p>结合以上分析，collect()方法定义为<R> R collect(Supplier<R> supplier, BiConsumer&lt;R,? super T&gt; accumulator, BiConsumer&lt;R,R&gt; combiner)，三个参数依次对应上述三条分析。不过每次调用collect()都要传入这三个参数太麻烦，收集器Collector就是对这三个参数的简单封装,所以collect()的另一定义为&lt;R,A&gt; R collect(Collector&lt;? super T,A,R&gt; collector)。Collectors工具类可通过静态方法生成各种常用的Collector。举例来说，如果要将Stream规约成List可以通过如下两种方式实现：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;String&gt; stream &#x3D; Stream.of(&quot;I&quot;,&quot;love&quot;,&quot;you&quot;,&quot;too&quot;);</span><br><span class="line">List&lt;String&gt; list &#x3D; stream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);</span><br><span class="line">&#x2F;&#x2F;List&lt;String&gt; list &#x3D; stream.collect(Collectors.toList());</span><br><span class="line">System.out.println(list);</span><br></pre></td></tr></table></figure>

<p>通常情况下我们不需要手动指定collect()的三个参数，而是调用collect(Collector&lt;? super T,A,R&gt; collector)方法，并且参数中的Collector对象大都是直接通过Collectors工具类获得。实际上传入的收集器的行为决定了collect()的行为。</p>
<p>==使用collect()生成Collection==</p>
<p>前面已经提到通过collect()方法将Stream转换成容器的方法，这里再汇总一下。将Stream转换成List或Set是比较常见的操作，所以Collectors工具已经为我们提供了对应的收集器，通过如下代码即可完成：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 将Stream转换成List或Set</span><br><span class="line">Stream&lt;String&gt; stream &#x3D; Stream.of(&quot;I&quot;, &quot;love&quot;, &quot;you&quot;, &quot;too&quot;);</span><br><span class="line">List&lt;String&gt; list &#x3D; stream.collect(Collectors.toList()); &#x2F;&#x2F; (1)</span><br><span class="line">Set&lt;String&gt; set &#x3D; stream.collect(Collectors.toSet()); &#x2F;&#x2F; (2)</span><br></pre></td></tr></table></figure>

<p>上述代码能够满足大部分需求，但由于返回结果是接口类型，我们并不知道类库实际选择的容器类型是什么，有时候我们可能会想要人为指定容器的实际类型，这个需求可通过Collectors.toCollection(Supplier<C> collectionFactory)方法完成。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; list &#x3D; stream.collect(Collectors.toCollection(ArrayList::new)); &#x2F;&#x2F;(3)</span><br><span class="line">Set&lt;String&gt; set &#x3D; stream.collect(Collectors.toCollection(HashSet::new));  &#x2F;&#x2F;(4)</span><br></pre></td></tr></table></figure>
<p>上述代码(3)处指定规约结果是ArrayList，而(4)处指定规约结果为HashSet。一切如你所愿。</p>
<h4 id="使用collect-生成Map"><a href="#使用collect-生成Map" class="headerlink" title="==使用collect()生成Map=="></a>==使用collect()生成Map==</h4><p>前面已经说过Stream背后依赖于某种数据源，数据源可以是数组、容器等，但不能是Map。反过来从Stream生成Map是可以的，但我们要想清楚Map的key和value分别代表什么，根本原因是我们要想清楚要干什么。通常在三种情况下collect()的结果会是Map：</p>
<ol>
<li>使用Collectors.toMap()生成的收集器，用户需要指定如何生成Map的key和value。</li>
<li>使用Collectors.partitioningBy()生成的收集器，对元素进行二分区操作时用到。</li>
<li>使用Collectors.groupingBy()生成的收集器，对元素做group操作时用到。</li>
</ol>
<ul>
<li>情况1：使用toMap()生成的收集器，这种情况是最直接的，前面例子中已提到，这是和Collectors.toCollection()并列的方法。如下代码展示将电脑列表转换成由&lt;电脑，G价格&gt;组成的Map。非常直观，无需多言。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">public void TestCollectMap() &#123;</span><br><span class="line">    List&lt;ComputerVO&gt; computers &#x3D; new ArrayList&lt;&gt;();</span><br><span class="line">    computers.add(new ComputerVO(&quot;联想笔记本&quot;,5500.0));</span><br><span class="line">    computers.add(new ComputerVO(&quot;华硕笔记本&quot;,3500.0));</span><br><span class="line">    computers.add(new ComputerVO(&quot;苹果笔记本&quot;,6500.0));</span><br><span class="line">    Map&lt;ComputerVO,Double&gt; map &#x3D; computers.stream().collect(Collectors.toMap(Function.identity(), computerVO -&gt; getComputerPrice(computerVO)));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">private Double getComputerPrice(ComputerVO computerVO) &#123;</span><br><span class="line">    return computerVO.getPrice();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>情况2：使用partitioningBy()生成的收集器，这种情况适用于将Stream中的元素依据某个二值逻辑（满足条件，或不满足）分成互补相交的两部分，比如男女性别、成绩及格与否等。下列代码展示将电脑分成价格大于等于3500和小于3500的两部分。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public void TestcollectMap2() &#123;</span><br><span class="line">    List&lt;ComputerVO&gt; computers &#x3D; new ArrayList&lt;&gt;();</span><br><span class="line">    computers.add(new ComputerVO(&quot;联想笔记本&quot;,5500.0));</span><br><span class="line">    computers.add(new ComputerVO(&quot;华硕笔记本&quot;,3500.0));</span><br><span class="line">    computers.add(new ComputerVO(&quot;苹果笔记本&quot;,6500.0));</span><br><span class="line">    Map&lt;Boolean,List&lt;ComputerVO&gt;&gt; map &#x3D; computers.stream().collect(Collectors.partitioningBy(c -&gt; c.getPrice() &gt;&#x3D; 3500));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>情况3：使用groupingBy()生成的收集器，这是比较灵活的一种情况。跟SQL中的group by语句类似，这里的groupingBy()也是按照某个属性对数据进行分组，属性相同的元素会被对应到Map的同一个key上。下列代码展示将电脑按照品牌进行分组：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">List&lt;ComputerVO&gt; computers &#x3D; new ArrayList&lt;&gt;();</span><br><span class="line">computers.add(new ComputerVO(&quot;联想笔记本&quot;,5500.0));</span><br><span class="line">computers.add(new ComputerVO(&quot;华硕笔记本&quot;,3500.0));</span><br><span class="line">computers.add(new ComputerVO(&quot;苹果笔记本&quot;,6500.0));</span><br><span class="line">Map&lt;String,List&lt;ComputerVO&gt;&gt; map &#x3D; computers.stream().collect(Collectors.groupingBy(ComputerVO::getName));</span><br></pre></td></tr></table></figure>

<p>以上只是分组的最基本用法，有些时候仅仅分组是不够的。在SQL中使用group by是为了协助其他查询，比如1. 先将电脑按照品牌分组，2. 然后统计每个品牌电脑的个数。Java类库设计者也考虑到了这种情况，增强版的groupingBy()能够满足这种需求。增强版的groupingBy()允许我们对元素分组之后再执行某种运算，比如求和、计数、平均值、类型转换等。这种先将元素分组的收集器叫做==上游收集器==，之后执行其他运算的收集器叫做==下游收集器==(downstream Collector)。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">List&lt;ComputerVO&gt; computers &#x3D; new ArrayList&lt;&gt;();</span><br><span class="line">computers.add(new ComputerVO(&quot;联想笔记本&quot;,5500.0));</span><br><span class="line">computers.add(new ComputerVO(&quot;华硕笔记本&quot;,3500.0));</span><br><span class="line">computers.add(new ComputerVO(&quot;苹果笔记本&quot;,6500.0));</span><br><span class="line">Map&lt;String, Long&gt; map &#x3D; computers.stream().collect(Collectors.groupingBy(ComputerVO::getName, Collectors.counting()));</span><br></pre></td></tr></table></figure>

<p>上面代码的逻辑是不是越看越像SQL？高度非结构化。还有更狠的，下游收集器还可以包含更下游的收集器，这绝不是为了炫技而增加的把戏，而是实际场景需要。考虑将员工按照部门分组的场景，如果我们想得到每个员工的名字（字符串），而不是一个个Employee对象，可通过如下方式做到：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 按照部门对员工分布组，并只保留员工的名字</span><br><span class="line">Map&lt;Department, List&lt;String&gt;&gt; byDept &#x3D; employees.stream()</span><br><span class="line">                .collect(Collectors.groupingBy(Employee::getDepartment,</span><br><span class="line">                        Collectors.mapping(Employee::getName,&#x2F;&#x2F; 下游收集器</span><br><span class="line">                                Collectors.toList())));&#x2F;&#x2F; 更下游的收集器</span><br></pre></td></tr></table></figure>

<h4 id="使用collect-做字符串join"><a href="#使用collect-做字符串join" class="headerlink" title="==使用collect()做字符串join=="></a>==使用collect()做字符串join==</h4><p>这个肯定是大家喜闻乐见的功能，字符串拼接时使用Collectors.joining()生成的收集器，从此告别for循环。Collectors.joining()方法有三种重写形式，分别对应三种不同的拼接方式。无需多言，代码过目难忘。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 使用Collectors.joining()拼接字符串</span><br><span class="line">Stream&lt;String&gt; stream &#x3D; Stream.of(&quot;I&quot;, &quot;love&quot;, &quot;you&quot;);</span><br><span class="line">&#x2F;&#x2F;String joined &#x3D; stream.collect(Collectors.joining());&#x2F;&#x2F; &quot;Iloveyou&quot;</span><br><span class="line">&#x2F;&#x2F;String joined &#x3D; stream.collect(Collectors.joining(&quot;,&quot;));&#x2F;&#x2F; &quot;I,love,you&quot;</span><br><span class="line">String joined &#x3D; stream.collect(Collectors.joining(&quot;,&quot;, &quot;&#123;&quot;, &quot;&#125;&quot;));&#x2F;&#x2F; &quot;&#123;I,love,you&#125;&quot;</span><br></pre></td></tr></table></figure>

<h4 id="collect-还可以做更多"><a href="#collect-还可以做更多" class="headerlink" title="==collect()还可以做更多=="></a>==collect()还可以做更多==</h4><p>除了可以使用Collectors工具类已经封装好的收集器，我们还可以自定义收集器，或者直接调用collect(Supplier<R> supplier, BiConsumer&lt;R,? super T&gt; accumulator, BiConsumer&lt;R,R&gt; combiner)方法，收集任何形式你想要的信息。不过Collectors工具类应该能满足我们的绝大部分需求，手动实现之间请先看看文档。</p>
<h1 id="3、深入理解Java"><a href="#3、深入理解Java" class="headerlink" title="3、深入理解Java"></a>3、深入理解Java</h1><p><a href="http://www.importnew.com/24235.html" target="_blank" rel="noopener">http://www.importnew.com/24235.html</a></p>
<p><a href="http://www.importnew.com/25315.html" target="_blank" rel="noopener">http://www.importnew.com/25315.html</a></p>
<h1 id="参考文档"><a href="#参考文档" class="headerlink" title="参考文档"></a>参考文档</h1><p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#package.description" target="_blank" rel="noopener">https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#package.description</a><br><a href="https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html" target="_blank" rel="noopener">https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html</a><br><a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html" target="_blank" rel="noopener">https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html</a><br><a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html" target="_blank" rel="noopener">https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html</a><br><a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html" target="_blank" rel="noopener">https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html</a></p>
<p><a href="http://www.importnew.com/24237.html" target="_blank" rel="noopener">http://www.importnew.com/24237.html</a><br><a href="http://www.importnew.com/24245.html" target="_blank" rel="noopener">http://www.importnew.com/24245.html</a><br><a href="http://www.importnew.com/24235.html" target="_blank" rel="noopener">http://www.importnew.com/24235.html</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="Richey Liu 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Richey Liu 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Richey Liu
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://10000hours.top/2019/03/08/Java%20Stream/" title="Java Stream">http://10000hours.top/2019/03/08/Java%20Stream/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/lambda/" rel="tag"># lambda</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/03/08/Java%E5%9F%BA%E7%A1%80/" rel="next" title="Java基础">
                <i class="fa fa-chevron-left"></i> Java基础
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/03/08/hexo%E5%91%BD%E4%BB%A4/" rel="prev" title="hexo命令">
                hexo命令 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="Richey Liu" />
            
              <p class="site-author-name" itemprop="name">Richey Liu</p>
              <p class="site-description motion-element" itemprop="description">花有重开时人无再少年</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">131</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">24</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">42</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/liubaolin" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-globe"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="brin.baolin@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-globe"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1、Java-Stream-API-入门"><span class="nav-number">1.</span> <span class="nav-text">1、Java Stream API 入门</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Java8引入函数式编程"><span class="nav-number">1.1.</span> <span class="nav-text">Java8引入函数式编程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java函数式编程的主角-Stream"><span class="nav-number">1.2.</span> <span class="nav-text">Java函数式编程的主角 Stream</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Stream的特点"><span class="nav-number">1.3.</span> <span class="nav-text">Stream的特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Stream常见方法"><span class="nav-number">1.4.</span> <span class="nav-text">Stream常见方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Stream方法的使用"><span class="nav-number">1.5.</span> <span class="nav-text">Stream方法的使用</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2、Java-Stream-API-进阶"><span class="nav-number">2.</span> <span class="nav-text">2、Java Stream API 进阶</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Stream的规约操作"><span class="nav-number">2.1.</span> <span class="nav-text">Stream的规约操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#多面手reduce"><span class="nav-number">2.1.1.</span> <span class="nav-text">多面手reduce()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#终极武器collect"><span class="nav-number">2.1.2.</span> <span class="nav-text">终极武器collect()</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#接口的静态方法和默认方法"><span class="nav-number">2.1.2.1.</span> <span class="nav-text">&#x3D;&#x3D;接口的静态方法和默认方法&#x3D;&#x3D;</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#方法引用"><span class="nav-number">2.1.2.2.</span> <span class="nav-text">&#x3D;&#x3D;方法引用&#x3D;&#x3D;</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#收集器"><span class="nav-number">2.1.2.3.</span> <span class="nav-text">&#x3D;&#x3D;收集器&#x3D;&#x3D;</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用collect-生成Map"><span class="nav-number">2.1.2.4.</span> <span class="nav-text">&#x3D;&#x3D;使用collect()生成Map&#x3D;&#x3D;</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用collect-做字符串join"><span class="nav-number">2.1.2.5.</span> <span class="nav-text">&#x3D;&#x3D;使用collect()做字符串join&#x3D;&#x3D;</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#collect-还可以做更多"><span class="nav-number">2.1.2.6.</span> <span class="nav-text">&#x3D;&#x3D;collect()还可以做更多&#x3D;&#x3D;</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3、深入理解Java"><span class="nav-number">3.</span> <span class="nav-text">3、深入理解Java</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考文档"><span class="nav-number">4.</span> <span class="nav-text">参考文档</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Richey Liu</span>

  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'espIarB7yj7vR1el85iiMLjb-gzGzoHsz',
        appKey: 'v35zFd1Yc4PX5KsGn2wHgrob',
        placeholder: '欢迎留言！',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("98BykxDu7C0UsRu0zaggGlMu-gzGzoHsz", "a21Q7nym42YYGdxdx2XxxQNM");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
